import numpy as np
from pyzbar.pyzbar import decode
from PIL import Image
import tkinter
from tkinter import *
from tkinter.messagebox import showinfo,showerror
import windnd
from PIL import Image
import os,sys
def resource_path(relative_path):
    if getattr(sys, 'frozen', False):
        base_path = sys._MEIPASS
    else:
        #base_path = os.path.abspath(".")
        base_path = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(base_path, relative_path)
def dragged_files(files) :
    global a
    a.delete(1.0,END)
    errowlist=[]

    for image in files:
        errname=""
        if len(image)>30:
            errname="..."+image.decode("gbk")[-30:]
        else:
            errname=image.decode("gbk")
        image=image.decode("gbk")
        try:
            img = Image.open(image)
        except:
            if len(files)==1:
                showerror("ERROW: Fail to open the file","文件"+image+"打开失败,请选择合适的文件类型,或确认文件是否损坏。")
            errowlist.append("文件"+errname+"打开失败.")
            continue
        try:
            barcodes = decode(img)
        except:
            if len(files)==1:
                showerror("ERROW: Fail to Search the file","文件"+image+"搜索失败.")
            errowlist.append("文件"+errname+"搜索失败.")
            continue
        barcodes = decode(img)
        
        if len(barcodes)==0:
            if len(files)==1:
                showinfo("INFO: The Photo Has No Recognizable Info","在"+image+"中未找到二维码或二维码不包含可识别信息.")
            errowlist.append("文件"+errname+"无有效信息.")
            continue
        a.insert(END,"我们从"+errname+"中读取到了以下结果:\n")
        for barcode in barcodes:
            url = barcode.data.decode("utf-8")
            a.insert(END,url+"\n")
            print(url)
    for i in errowlist:
        print(i)
        a.insert(END,i+"\n")


tk = tkinter.Tk()
tk.iconbitmap(resource_path(os.path.join("logo.ico")))
tk.title("二维码识别")
tk.geometry("550x500")
w =Scrollbar()
w.grid(column=1, row=0,columnspan=1,rowspan=2,sticky=N+S)
a= tkinter.Text(tk,yscrollcommand=w.set,width=70,height = 70)
w.config(command=a.yview)
a.insert(END,"请拖入二维码文件")
a.grid(column=0, row=0)
windnd.hook_dropfiles(tk, func=dragged_files)
tk.mainloop()
